<template>
  <div>
    <!-- action:用来制定文件要上传的地址
         show-file-list:是否显示上传的文件列表
         on-success:上传成功之后的回调
         before-upload:上传之前的回调
         http-request:自定义上传行为
    -->
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <!-- 进度条 -->
      <el-progress v-if="showProgress" :percentage="percent"/>
    </el-upload>
  </div>
</template>

<script>

 var COS = require('cos-js-sdk-v5');
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
    SecretId: 'AKIDnSt65pKaaMxKTN5aqwnTv86qLbbLo1zi',
    SecretKey: 'Xpqb9TWLuEDwPcZG8l8FsFPJxKRVVRDm',
});
export default {
  props:{
    value:{
     type:String,
     default:''
    }
  },
  data() {
    return {
      imageUrl: '',
      percent:0 ,
      showProgress:false
    }
  },
  methods: {
    upload(res) {
      console.log(res)
  // 1.将文件对象上传到腾讯云
  if(res.file){
    this.showProgress = true  // 上传时打来进度条
   cos.putObject({
      Bucket: 'wh81-1257017897', /* 必须 */
      Region: 'ap-nanjing',     /* 存储桶所在地域，必须字段 */
      Key: res.file.name,              /* 文件名*/
      StorageClass: 'STANDARD',      // 上传模式
      Body: res.file, // 上传文件对象
      // 监控文件上传的进度
      onProgress:(progressData) => {
       console.log(progressData);
       this.percent = progressData.percent * 100
      }
}, (err, data)=>{
    // 无论上传成功还是失败,都会执行该回调函数
    console.log(err || data);
    this.$emit('input',`https:${data.Location}`) // 上传成功将图片路径传给父组件
    this.showProgress = false  // 上传完隐藏进度条
    if(data.statusCode === 200){
     this.imageUrl = `https:${data.Location}`
     console.log(this.imageUrl);
    }
});
    }
  },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG &&  isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>